package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.dto.response.ServeItemResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.enums.FoundationHotEnum;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.mapper.ServeSyncMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.domain.ServeSync;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeAggregationSimpleResDTO;
import com.jzo2o.foundations.model.dto.response.ServeAggregationTypeSimpleResDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-03
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    private final ServeItemMapper serveItemMapper;
    private final RegionMapper regionMapper;
    private final ServeMapper serveMapper;
    private final ServeSyncMapper serveSyncMapper;

    public ServeServiceImpl(ServeItemMapper serveItemMapper, RegionMapper regionMapper, ServeMapper serveMapper, ServeSyncMapper serveSyncMapper) {
        this.serveItemMapper = serveItemMapper;
        this.regionMapper = regionMapper;
        this.serveMapper = serveMapper;
        this.serveSyncMapper = serveSyncMapper;
    }

    /**
     * 分页查询
     *
     * @param servePageQueryReqDTO 查询条件
     * @return 分页结果
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //通过baseMapper调用queryServeListByRegionId方法
        return PageHelperUtils.selectPage(servePageQueryReqDTO, () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }

    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        for (ServeUpsertReqDTO serveUpsertReqDTO : serveUpsertReqDTOList) {
            //检查合法性
            //检查服务的启用状态
            ServeItem serveItem = serveItemMapper.selectById(serveUpsertReqDTO.getServeItemId());
            if (ObjectUtil.isNull(serveItem) || serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
                throw new ForbiddenOperationException("该服务不存在或未启用!");
            }
            //检查服务是否已经存在
            Integer count = lambdaQuery()
                    .eq(Serve::getServeItemId, serveUpsertReqDTO.getServeItemId())
                    .eq(Serve::getRegionId, serveUpsertReqDTO.getRegionId())
                    .count();
            if (count >= 1) {
                throw new ForbiddenOperationException("该服务已存在!");
            }
            Serve serve = BeanUtil.toBean(serveUpsertReqDTO, Serve.class);
            Region region = regionMapper.selectById(serveUpsertReqDTO.getRegionId());
            serve.setCityCode(region.getCityCode());
            baseMapper.insert(serve);
        }
    }

    @Override
    public Serve update(Long id, BigDecimal price) {
        boolean update = lambdaUpdate()
                .set(Serve::getPrice, price)
                .eq(Serve::getId, id)
                .update();
        if (!update) {
            throw new ForbiddenOperationException("更新价格失败!");
        }
        Serve serve = baseMapper.selectById(id);
        return serve;
    }

/*    @Override
    public void updateStatus(Long id, int status) {
        Serve serve = baseMapper.selectById(id);
        if(serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("该服务已启用!");
        }
        if(serve.getSaleStatus()!= FoundationStatusEnum.INIT.getStatus()&&serve.getSaleStatus()!=FoundationStatusEnum.DISABLE.getStatus()){
            throw new ForbiddenOperationException("该服务不允许启用!");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, status)
                .update();
        if(!update){
            throw new ForbiddenOperationException("启用失败!");
        }
    }*/

    @Override
    public void onSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("该服务不存在!");
        }
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("该服务已启用!");
        }
        if (serve.getSaleStatus() != FoundationStatusEnum.INIT.getStatus() && serve.getSaleStatus() != FoundationStatusEnum.DISABLE.getStatus()) {
            throw new ForbiddenOperationException("该服务不允许启用!");
        }
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if (serveItem.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("服务项的状态未启动不能上架");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("启用失败!");
        }
    }

    @Override
    public void del(Long id) {
        Serve serve = serveMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("不存在的服务");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("serveItemId", serve.getServeItemId().toString());
        map.put("cityCode", serve.getCityCode().toString());
        List<ServeSync> serveSyncs = serveSyncMapper.selectByMap(map);
        if (ObjectUtil.isNotEmpty(serveSyncs)) {
            throw new ForbiddenOperationException("有存在的服务,不允许删除!");
        }
        if (serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("已启用的服务,不允许删除");
        }
        int i = serveMapper.deleteById(id);
        if (i < 1) {
            throw new ForbiddenOperationException("删除失败");
        }
    }

    @Override
    public void offSale(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("该服务不存在!");
        }
        if (serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()) {
            throw new ForbiddenOperationException("该服务未启用!");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("下架失败!");
        }
    }

    @Override
    public void onHot(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("该服务不存在!");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationHotEnum.ENABLE.getStatus())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("更新失败!");
        }
    }

    @Override
    public void offHot(Long id) {
        Serve serve = baseMapper.selectById(id);
        if (ObjectUtil.isNull(serve)) {
            throw new ForbiddenOperationException("该服务不存在!");
        }
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, FoundationHotEnum.DISABLE.getStatus())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("更新失败!");
        }
    }

    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long id, int status) {
        LambdaQueryWrapper<Serve> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Serve::getRegionId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus());
        return serveMapper.selectCount(lqw);
    }

    @Override
    public int queryServeCountByServeItemIdAndSaleStatus(Long id, int status) {
        LambdaQueryWrapper<Serve> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Serve::getServeItemId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus());
        return serveMapper.selectCount(lqw);
    }

    @Override
    @Cacheable(value = RedisConstants.CacheName.SERVE_REGION, key = "#regionId", cacheManager = RedisConstants.CacheManager.FOREVER)
    public List<ServeAggregationTypeSimpleResDTO> getByRegionId(Long regionId) {
        List<ServeAggregationTypeSimpleResDTO> serves = serveMapper.selectListByRegionAndSaleStatus(regionId, 2);
        return serves;
    }

    @Override
    @Caching(
            cacheable = {
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key = "#regionId", cacheManager = RedisConstants.CacheManager.FOREVER, unless = "#result.length()==0"),
                    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE, key = "#regionId", cacheManager = RedisConstants.CacheManager.THIRTY_MINUTES, unless = "#result.length()!=0")
            }
    )
    public List<ServeAggregationSimpleResDTO> getHotServeListByRegionId(Long regionId) {
        return serveMapper.getServeListByRegionIdAndIsHot(regionId, 1);
    }

    @Override
    public ServeAggregationSimpleResDTO getServeById(Long id) {
        Serve serve =this.getByIdAndCache(id);
        ServeItem serveItem = this.getServeItemById(serve.getServeItemId());
        ServeAggregationSimpleResDTO serveAggregationSimpleResDTO = new ServeAggregationSimpleResDTO();
        BeanUtil.copyProperties(serve,serveAggregationSimpleResDTO);
        BeanUtil.copyProperties(serveItem,serveAggregationSimpleResDTO);
        return serveAggregationSimpleResDTO;
    }

    @CachePut(value = RedisConstants.CacheName.SERVE_ITEM,key="#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    public ServeItem getServeItemById(Long id){
        return serveItemMapper.selectById(id);
    }

    @CachePut(value = RedisConstants.CacheName.SERVE,key = "#id",cacheManager = RedisConstants.CacheManager.ONE_DAY)
    public Serve getByIdAndCache(Long id){
        return serveMapper.selectById(id);
    }

}